package org.budo.maven.plugin.assembly.mojo.processor;

import java.io.File;
import java.io.InputStream;
import java.net.URL;

import org.apache.commons.lang3.StringUtils;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.budo.support.lang.util.FileUtil;
import org.budo.support.lang.util.IoUtil;

/**
 * @author lmw
 */
public class BudoMavenSpringBootProcessor extends AbstractBudoMavenAssemblyProcessor {
    private static final String BIN_DIR = "budo-maven-assembly-bin-spring-boot";

    private static final String[] BIN_FILES = { "sp1.sh", "sp2.sh" };

    public BudoMavenSpringBootProcessor(MavenProject project, MavenSession session, String format, Log log) {
        super(project, session, format, log);
    }

    @Override
    public void execute() throws Throwable {
        this.getLog().info("#27 BudoMavenSpringBootProcessor#execute project.artifact=" + this.getProject().getArtifact() //
                + ", project.base=" + this.getProject().getBasedir() + ", format=" + this.getFormat() + ", this=" + this);

        String _target = this.getProject().getBuild().getDirectory();
        File target = new File(_target);

        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        this.getLog().info("#37 writeBinFiles, " + StringUtils.join(BIN_FILES, ", ") + " > " + target.getCanonicalPath() + ", classLoader=" + classLoader);

        URL assemblyBin = classLoader.getResource(BIN_DIR);

        for (String binFile : BIN_FILES) {
            InputStream from = this.resourceInputStream(BIN_DIR, binFile);
            if (null == from) {
                this.getLog().error("#241 binFile " + binFile + " not found, assemblyBin=" + assemblyBin);
                continue;
            }

            // 脚本
            String scriptTemplate = IoUtil.toString(from);
            String mergedScript = this.mergeTemplate(scriptTemplate);

            File toAssembly = new File(new File(target.getParentFile(), "assembly-target").getCanonicalPath() + File.separator + binFile);
            IoUtil.write(mergedScript, IoUtil.fileOutputStream(toAssembly));
            this.getLog().info("#53 binFile=" + binFile + ", to=" + FileUtil.getCanonicalPath(toAssembly));
        }
    }
}